import cloud from '@lafjs/cloud'
import { getLoginUrl } from "@/thirdParty/moxueyuanUtils";

let userId
let ctxData

export default async function (ctx: FunctionContext) {
  ctxData = ctx.body.data

  if (cloud.utils.isString(ctx.user.uid)) {
    userId = ctx.user.uid
  } else {
    userId = ctx.user.uid._id
  }

  switch (ctx.body.type) {
    case "details":
      return getDetails()
      break;
    case "update":
      return update()
      break;
    case "moxueyuanLoginUrl":
      return getMoxueyuanLoginUrl()
      break;
    default:
      break;
  }


}

async function getDetails() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName: "web-users",
    fieldJson: {
      nickname: 1,
      headimgurl: 1,
      mobile: 1,
      baseInfo: 1
    },
    whereJson: { _id: userId },
  });
  return cloud.utils.requestReturn({ data: res })
}

async function update() {
  await cloud.nw.db.update({
    dbName: "web-users",
    whereJson: { _id: userId },
    dataJson: ctxData
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function getMoxueyuanLoginUrl() {
  let url = await getLoginUrl({ userId, type: ctxData.type })
  return cloud.utils.requestReturn({ data: url })
}